'use client';

import { useState } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';

type SavedUser = {
  id: string;
  name: string | null;
};

export function SaveButton({
  destinationId,
  savedBy
}: {
  destinationId: string;
  savedBy: SavedUser[];
}) {
  const router = useRouter();
  const { data: session } = useSession();
  const [isSaved, setIsSaved] = useState(
    savedBy?.some(user => user.id === session?.user?.id) || false
  );
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSave = async () => {
    if (!session) {
      router.push('/api/auth/signin');
      return;
    }

    setIsSubmitting(true);
    try {
      const response = await fetch(`/api/destinations/${destinationId}/save`, {
        method: isSaved ? 'DELETE' : 'POST',
      });

      if (!response.ok) {
        throw new Error('保存失败');
      }

      setIsSaved(!isSaved);
      router.refresh();
    } catch (error) {
      console.error('Save error:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <button
      onClick={handleSave}
      disabled={isSubmitting}
      className={`p-2 rounded-full transition-colors ${
        isSaved 
          ? 'text-pink-600 bg-pink-50 hover:bg-pink-100' 
          : 'text-gray-400 hover:text-pink-600 hover:bg-pink-50'
      }`}
    >
      <svg 
        className="w-6 h-6" 
        fill={isSaved ? "currentColor" : "none"} 
        stroke="currentColor" 
        viewBox="0 0 24 24"
      >
        <path 
          strokeLinecap="round" 
          strokeLinejoin="round" 
          strokeWidth={2} 
          d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" 
        />
      </svg>
    </button>
  );
} 